﻿namespace QuickMail.View.Controls
{
    using System.Diagnostics;
    using System.Globalization;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;

    using QuickMail.BusinessLogic;
    using QuickMail.DataModels;
    using QuickMail.ViewModels;

    /// <summary>
    /// Form to display the message.
    /// </summary>
    public partial class MessageControl
    {
        public LetterVm CurrentLetterVm;

        /// <summary>
        /// Creates new control
        /// </summary>
        public MessageControl()
        {
            InitializeComponent();
            SetCurrentTranslate();
        }

        /// <summary>
        /// Sets the current translation for form elements.
        /// </summary>
        private void SetCurrentTranslate()
        {
            NextTextBlock.Text = StaticFields.Lang.MainWindow.Next;
            PreviousTextBlock.Text = StaticFields.Lang.MainWindow.Previous;
            DeleteTextBlock.Text = StaticFields.Lang.MainWindow.Delete;
            FromTitleTextBlock.Text = StaticFields.Lang.MainWindow.FromColumn;
            ToTitleTextBlock.Text = StaticFields.Lang.MainWindow.ToColumn;
        }

        /// <summary>
        /// Load current letter to form
        /// </summary>
        public void Load(LetterVm letterVm)
        {
            CurrentLetterVm = letterVm;
            FromTextBlock.Text = letterVm.From;
            ToTextBlock.Text = letterVm.To;
            DateTextBlock.Text = letterVm.LetterDate.ToString("f");
            SubjectTextBlock.Text = letterVm.Subject;

            BrowserBehavior.SetHtml(MessageBrowser, letterVm.MessageText);

            AttachmentsWrapPanel.Children.Clear();
            foreach (var fileMetadata in letterVm.FileVms)
            {
                AttachmentsWrapPanel.Children.Add(new Button
                {
                    Style = (Style)Resources["FileButtonStyle"],
                    Margin = new Thickness(5, 5, 5, 5),
                    Tag = HelpWorker.GetFileImage(fileMetadata.Extention),
                    Content = fileMetadata.FileName,
                    ToolTip = fileMetadata.FileName,
                    CommandParameter = Path.Combine(StaticFields.ResourcesPath,
                        letterVm.Id.ToString(CultureInfo.InvariantCulture), fileMetadata.FileName)
                });
            }
        }

        /// <summary>
        /// Opens folder in the explorer.
        /// </summary>
        private void OpenFolder_OnClick(object sender, RoutedEventArgs e)
        {
            if (CurrentLetterVm == null)
                return;

            Process.Start("explorer.exe", Path.Combine(StaticFields.ResourcesPath, 
                CurrentLetterVm.Id.ToString(CultureInfo.InvariantCulture)));
        }
    }
}
